package py.com.alfa.escriba.gui.config;

import java.io.IOException;
import java.util.Properties;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

public class EscribaGUIContextListener implements ServletContextListener {
	Logger log = LoggerFactory.getLogger(getClass());
	
	static String buildNumber = "unknown";
	static String vendor = "unknown";
	static String version = "unknown";
	static String artifactName = "unknown";
	
	public EscribaGUIContextListener() {}

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		log.info("Stopped {} {} build {} by {}",new String[]{artifactName, version,buildNumber,vendor});
	}

	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		ApplicationContext ctx =  EscribaGUIApplicationContextProvider.getContext();
		log.info("Context: {}", ctx);
		Properties props = new Properties();
		
		try {
			props.load(ctx.getResource("classpath:build.number").getInputStream());
			buildNumber = props.getProperty("build.number");
			
			props.load(ctx.getResource("classpath:build.properties").getInputStream());
			vendor = props.getProperty("implementation.vendor");
			version = props.getProperty("implementation.version");
			artifactName = props.getProperty("artifact.name");
		} catch (IOException e) {
			log.warn("no data were found in properties file. not fatal. continuing");			
		} finally {
			props = null;
		}				
		log.info("Started {} {} build {} by {}",new String[]{artifactName, version,buildNumber,vendor});

	}

}
